package edu.towson.cosc.cosc455.cbrown.mdcomp;
import java.io.*;

public class MyCompiler {

	public static String token;
	public static MySynAnalyzer syn = new MySynAnalyzer();
	public static MyLexAnalyzer lex = syn.lex;
	public static MySemAnalyzer sem = new MySemAnalyzer();
	
	public static void main(String[] args) throws CompilerException, IOException, NullPointerException{
		String file;
		String fileName;
		
		// 1. Check to make sure args is 1
		if (args.length == 1) {
			
		// 2. Check to make sure the file has a mkd extensions
			if (args[0].endsWith(".mkd")) {
				
		// 3. Initializations - tokens, setups of other variables
				file = readFile(args[0]);
				fileName = args[0].replace(".mkd", "");
				token = "";
 				
		
		// 4. Call the lexical analyzer to get first token set
				lex.start(file);
				
		// 5. Call the start state of the parser, i.e., document()
				syn.document();
		
		// 6. Call the semantic analyzer
				sem.start();
				
		// 7. Write the output file to html
				PrintWriter output = new PrintWriter(fileName + ".html");
				
				for(int i = 0; i < sem.output.size(); i++) 
					output.println(sem.output.get(i));
					
		// 8. Clean up -> close the file, etc (not much in this case)
				output.close();
			}
			
			else
				System.out.println("Error: Only files with .mkd extension are accepted.");
		}
		
		else if (args.length >= 1)
			System.out.println("Error: Only one file can be used as input.");
		
		
		else
			System.out.println("Error: A file is needed as input.");
		
	}
	
	// Reads file into a string line by line
	// At end of file, returns file as single string.
	private static String readFile(String fileName) throws IOException {
	    BufferedReader br = new BufferedReader(new FileReader(fileName));
	        StringBuilder sb = new StringBuilder();
	        String line = br.readLine();

	        while (line != null) {
	            sb.append(line);
	            line = br.readLine();
	        }
	        br.close();
	        return sb.toString();
	}

}
